package endpoint

import (
	"mcode/apps/admin/internal/entity"
	"mcode/apps/admin/internal/usecase"
	"mcode/pkg/ctx"
	"mcode/pkg/query"
	"mcode/pkg/response"
	"mcode/pkg/validator"

	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type RoleHandler struct {
	roleUseCase usecase.RoleUseCase
	validator   *validator.Validator
}

func NewRoleHandler(roleUseCase usecase.RoleUseCase, validator *validator.Validator) *RoleHandler {
	return &RoleHandler{
		roleUseCase: roleUseCase,
		validator:   validator,
	}
}

func (h *RoleHandler) GetRole(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		response.Error(c, http.StatusBadRequest, "无效的ID")
		return
	}

	role, err := h.roleUseCase.GetRole(c.Request.Context(), uint(id))
	if err != nil {
		response.Error(c, http.StatusNotFound, "记录不存在")
		return
	}

	response.Success(c, role)
}

func (h *RoleHandler) UpdateRole(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		response.Error(c, http.StatusBadRequest, "无效的ID")
		return
	}

	role := new(entity.Role)
	if err := c.ShouldBindJSON(role); err != nil {
		response.Error(c, http.StatusBadRequest, "无效的请求数据")
		return
	}

	if err := h.validator.ValidateStruct(role); err != nil {
		errors := h.validator.TranslateError(err)
		response.ValidationError(c, errors)
		return
	}

	role.Id = uint(id)
	if err := h.roleUseCase.UpdateRole(c.Request.Context(), role); err != nil {
		response.Error(c, http.StatusInternalServerError, "更新失败")
		return
	}

	response.Success(c, role)
}

func (h *RoleHandler) DeleteRole(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		response.Error(c, http.StatusBadRequest, "无效的ID")
		return
	}

	if err := h.roleUseCase.DeleteRole(c.Request.Context(), uint(id)); err != nil {
		response.Error(c, http.StatusInternalServerError, "删除失败")
		return
	}

	response.Success(c, nil)
}

func (h *RoleHandler) CreateRole(c *gin.Context) {
	role := new(entity.Role)
	if err := c.ShouldBindJSON(role); err != nil {
		response.Error(c, http.StatusBadRequest, "无效的请求数据")
		return
	}

	if err := h.validator.ValidateStruct(role); err != nil {
		errors := h.validator.TranslateError(err)
		response.ValidationError(c, errors)
		return
	}

	if err := h.roleUseCase.CreateRole(c.Request.Context(), role); err != nil {
		response.Error(c, http.StatusInternalServerError, "创建失败")
		return
	}

	response.Success(c, role)
}

func (h *RoleHandler) ListRoles(c *gin.Context) {
	params := query.NewQuery().
		AddCondition("status", query.OpEq, 1).
		AddOrderBy("id DESC").
		SetPagination(ctx.GetPagination(c)).
		Select("id", "username", "email", "role", "status", "created_at", "updated_at")
	result, err := h.roleUseCase.List(c.Request.Context(), params)
	if err != nil {
		response.ServerError(c, err)
		return
	}

	response.Success(c, result)
}
